$(function(){
    console.log('来自于demo05');

    var searchKeys = $.Cache.get('searchHistory') || [];

    function fn_html_searchKeys(){
        if( searchKeys.length>0 ){
            $('.search_history dl').empty();
            var html_searchKeys = '<dt><div><span class="fl">历史搜索</span><span class="fr">清空历史记录</span></div></dt>';
            for( var i=searchKeys.length-1; i>=0; i--){
                html_searchKeys += '<dd><div>'+searchKeys[i]+'</div></dd>';
            }
            $('.search_history dl').append(html_searchKeys);
        }
    }
    fn_html_searchKeys();

    $('.search').focus(function(){
        var val = $(this).val();
        var historyNum = $('.search_history dd').length;
        if( val=='' && historyNum>0 ){
            $('.search_history').show();
        }
    }).keyup(function(e){
        var val = $(this).val();
        var historyNum = $('.search_history dd').length;

        if( val=='' && historyNum>0 ){
            $('.search_history').show();
        }else{
            $('.search_history').hide();
        }

        //按下回车键 搜索
        if( e.keyCode==13 ){

            var searchKey = $(this).val();

            if( searchKey.length>0 ){
                searchKeys.push(searchKey);
                $.unique(searchKeys);
                $.Cache.set('searchHistory', searchKeys, 0);
            }
            $('.search_history dd').remove();
            fn_html_searchKeys();

            $.ajax({
                type: 'POST',
                data: {
                    searchKey: searchKey
                },
                url: '',
                success: function(res){

                },
                error: function(){
                    toastr.error('查询失败');
                }
            });

        }

    });

    $('.searchWrap').mouseleave(function(){
        $('.search').blur();
        $('.search_history').hide();
    });

    //点击历史记录的关键词搜索
    $('body').on('click', '.search_history dd', function(){
        var val = $(this).text();
        $('.search').val(val).focus().siblings('.search_history').hide();
    });

    //清空搜索历史记录
    $('body').on('click', '.search_history .fr',function(){
        $('.search_history').hide();
        $('.pop').show();
    });
    $('#pop_del_searchkeys .cancel,.pop .close').click(function(){
        $(this).closest('.pop').hide();
    });
    $('#pop_del_searchkeys .confirm').click(function(){
        $.Cache.remove('searchHistory');
        searchKeys = [];
        $('.search_history dl').empty();
        $(this).closest('.pop').hide();
    });
});